// com.example.controller.PlanController.java
package com.example.controller;

import com.example.entity.Plan;
import com.example.service.PlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.Date;

@Controller
@RequestMapping("/plan")
public class PlanController {

    @Autowired
    private PlanService planService;

    // 显示所有计划
    @GetMapping("/list")
    public String list(Model model) {
        model.addAttribute("plans", planService.getAllPlans());
        return "plan/list";
    }

    // 显示添加计划表单
    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("plan", new Plan()); // 添加空Plan对象用于表单绑定
        return "plan/form";
    }

    // 处理添加计划
    @PostMapping("/add")
    public String addPlan(@ModelAttribute Plan plan) {
        planService.addPlan(plan);
        return "redirect:/plan/list";
    }

    // 显示编辑计划表单
    @GetMapping("/edit/{planid}")
    public String showEditForm(@PathVariable Integer planid, Model model) {
        Plan plan = planService.getPlanById(planid);
        model.addAttribute("plan", plan); // 添加从数据库查询的Plan对象
        return "plan/form";
    }

    // 处理编辑计划
    @PostMapping("/edit")
    public String editPlan(@ModelAttribute Plan plan) {
        planService.updatePlan(plan);
        return "redirect:/plan/list";
    }

    // 处理删除计划
    @GetMapping("/delete/{planid}")
    public String deletePlan(@PathVariable Integer planid) {
        planService.deletePlan(planid);
        return "redirect:/plan/list";
    }

    @Bean
    public DateFormatter dateFormatter() {
        return new DateFormatter("yyyy-MM-dd");
    }
}